<template>
  <div style="display: inline-flex; gap: 6px">
    <el-date-picker
      v-bind="$attrs"
      v-on="$listeners"
      v-model="beginTime"
      type="year"
      :editable="false"
      value-format="yyyy"
      placeholder="开始年"
      :append-to-body="false"
      :picker-options="limit ? pickerOptions : null"
      :align="align"
      @change="changeStart"
      class="monthRange"
      ref="datePickerstart"
    >
    </el-date-picker>
    -
    <el-date-picker
      v-on="$listeners"
      v-bind="$attrs"
      v-model="endTime"
      type="year"
      :editable="false"
      value-format="yyyy"
      placeholder="结束年"
      :append-to-body="false"
      :picker-options="limit ? pickerOptions : null"
      :align="align"
      @change="changeEnd"
      class="monthRange"
      ref="datePickerend"
    >
    </el-date-picker>
  </div>
</template>
<script>
export default {
  name: "YearRange",
  inheritAttrs: false,
  props: {
    value: {
      type: Array,
      require: true,
      default: [],
    },
    limit: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      align: "center",
      beginTime: "",
      endTime: "",
      lastDate: [],
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  watch: {
    value: {
      handler() {
        this.beginTime = this.value[0];
        this.endTime = this.value[1];
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    changeStart(time) {
      if (time > this.endTime * 1) {
        this.$modal.msgError("开始年份不能大于结束年份");
        this.beginTime = this.lastDate[0];
      } else {
        this.lastDate = [time, this.endTime];
        this.$emit("update:value", [time, this.endTime]);
      }
    },
    changeEnd(time) {
      if (time < this.beginTime * 1) {
        this.$modal.msgError("结束年份不能小于开始年份");
        this.endTime = this.lastDate[1];
      } else {
        this.lastDate = [this.beginTime, time];
        this.$emit("update:value", [this.beginTime, time]);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.monthRange {
  width: 110px;
}
</style>
